package zy.service.stock.data.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.base.bra.BraDAO;
import zy.dao.base.color.ColorDAO;
import zy.dao.base.size.SizeDAO;
import zy.dao.stock.data.DataDAO;
import zy.dao.sys.importinfo.ImportInfoDAO;
import zy.dto.common.TypeLevelDto;
import zy.dto.stock.data.ProductSingleTrackDto;
import zy.dto.stock.data.StockAnalysisDto;
import zy.dto.stock.data.StockDataByDepotDto;
import zy.dto.stock.data.StockReportByShopDto;
import zy.dto.stock.data.StockShopDto;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.base.bra.T_Base_Bra;
import zy.entity.base.color.T_Base_Color;
import zy.entity.base.size.T_Base_Size;
import zy.entity.base.size.T_Base_SizeList;
import zy.entity.base.type.T_Base_Type;
import zy.entity.stock.data.T_Stock_Data;
import zy.entity.stock.data.T_Stock_DataSizeView;
import zy.entity.stock.data.T_Stock_DataView;
import zy.entity.sys.improtinfo.T_Import_Info;
import zy.entity.sys.user.T_Sys_User;
import zy.form.NumberForm;
import zy.service.stock.data.DataService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.ExcelImportUtil;
import zy.util.StringUtil;
import zy.vo.base.TypeVO;
import zy.vo.sell.SellVO;

@Service
public class DataServiceImpl implements DataService{
	
	@Resource
	private DataDAO dataDAO;
	
	@Resource
	private SizeDAO sizeDAO;
	
	@Resource
	private BraDAO braDAO;
	
	@Resource
	private ColorDAO colorDAO;
	
	@Resource
	private ImportInfoDAO importInfoDAO;
	
	@Override
	public PageData<T_Stock_DataView> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		List<String> allDepot = dataDAO.listAllDepot(params);
		params.put("allDepot", allDepot);
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = dataDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Stock_DataView> list = dataDAO.list(params);
		PageData<T_Stock_DataView> pageData = new PageData<T_Stock_DataView>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		pageData.setData(dataDAO.sum(params));
		return pageData;
	}
	
	@Override
	public Map<String, List<T_Base_SizeList>> size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Map<String, List<T_Base_SizeList>> resultMap = new HashMap<String, List<T_Base_SizeList>>();
		List<String> allDepot = dataDAO.listAllDepot(params);
		params.put("allDepot", allDepot);
		List<String> szgCodes = dataDAO.list_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		for (T_Base_SizeList item : sizeGroupList) {
			if(!resultMap.containsKey(item.getSzl_szg_code())){
				resultMap.put(item.getSzl_szg_code(), new ArrayList<T_Base_SizeList>());
			}
			resultMap.get(item.getSzl_szg_code()).add(item);
		}
		return resultMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PageData<T_Stock_DataSizeView> size_data(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		
		List<String> allDepot = dataDAO.listAllDepot(params);
		params.put("allDepot", allDepot);
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		Map<String, Object> resultMap = dataDAO.size_data(params);
		Integer totalCount = (Integer)resultMap.get("totalCount");
		List<T_Stock_DataSizeView> listMain = (List<T_Stock_DataSizeView>)resultMap.get("listMain");
		List<T_Stock_Data> size_data = (List<T_Stock_Data>)resultMap.get("size_data");
		
		
		if (listMain.size() > 0 && size_data.size() > 0) {
			Map<String, List<T_Base_SizeList>> sizeGroupMap = new HashMap<String, List<T_Base_SizeList>>();
			List<String> szgCodes = dataDAO.list_szgcode(params);
			List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, (Integer)companyid);
			for (T_Base_SizeList item : sizeGroupList) {
				if(!sizeGroupMap.containsKey(item.getSzl_szg_code())){
					sizeGroupMap.put(item.getSzl_szg_code(), new ArrayList<T_Base_SizeList>());
				}
				sizeGroupMap.get(item.getSzl_szg_code()).add(item);
			}
			for (T_Stock_DataSizeView item : listMain) {
				List<T_Base_SizeList> sizeLists = sizeGroupMap.get(item.getPd_szg_code());
				if (sizeLists == null || sizeLists.size() == 0) {
					continue;
				}
				for (int i = 0; i < sizeLists.size(); i++) {
					for (T_Stock_Data stockData : size_data) {
						if(stockData.getSd_pd_code().equals(item.getSd_pd_code())
								&&stockData.getSd_cr_code().equals(item.getSd_cr_code())
								&&StringUtil.trimString(stockData.getSd_br_code()).equals(StringUtil.trimString(item.getSd_br_code()))
								&&stockData.getSd_sz_code().equals(sizeLists.get(i).getSzl_sz_code())){
							item.getAmountMap().put("size"+i, stockData.getSd_amount());
							break;
						}
					}
				}
			}
		}
		
		PageData<T_Stock_DataSizeView> pageData = new PageData<T_Stock_DataSizeView>();
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		pageData.setPageInfo(pageInfo);
		pageData.setList(listMain);
		pageData.setData(dataDAO.sum(params));
		return pageData;
	}
	
	@Override
	public PageData<StockDataByDepotDto> page_bydepot(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = dataDAO.count_bydepot(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<StockDataByDepotDto> list = dataDAO.list_bydepot(params);
		for (StockDataByDepotDto dto : list) {
			String depot_amount = dto.getDepot_amount();
			if(StringUtil.isEmpty(depot_amount)){
				continue;
			}
			String[] depotAmounts = depot_amount.split(",");
			for (String depotAmount : depotAmounts) {
				String[] temps = depotAmount.split(":");
				if(temps.length == 2){
					dto.getAmountMap().put(temps[0], Integer.parseInt(temps[1]));
				}
			}
		}
		PageData<StockDataByDepotDto> pageData = new PageData<StockDataByDepotDto>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		Map<String, Object> amountMap = new HashMap<String, Object>();
		List<Map<String, Object>> sumMaps = dataDAO.sum_bydepot(params);
		for (Map<String, Object> item : sumMaps) {
			amountMap.put(item.get("sd_dp_code").toString(), item.get("sd_amount"));
		}
		Map<String, Object> userData = new HashMap<String, Object>();
		userData.put("pd_no", "合计：");
		userData.put("amountMap", amountMap);
		pageData.setData(userData);
		return pageData;
	}
	
	@Override
	public PageData<StockReportByShopDto> page_byshop(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = dataDAO.count_byshop(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<StockReportByShopDto> list = dataDAO.list_byshop(params);
		for (StockReportByShopDto dto : list) {
			String shop_amountmoney = dto.getAmountmoney();//001:54_3042.00,002:-12_-673.80
			if(StringUtil.isEmpty(shop_amountmoney)){
				continue;
			}
			String[] shop_amountmoneys = shop_amountmoney.split(",");
			for (String item : shop_amountmoneys) {//001:54_3042.00
				String[] temps = item.split(":");
				if(temps.length != 2){
					continue;
				}
				String[] amount_money = temps[1].split("_");
				if(amount_money.length != 2){
					continue;
				}
				if(dto.getAmountMap().containsKey(temps[0])){
					dto.getAmountMap().put(temps[0], dto.getAmountMap().get(temps[0]) + Integer.parseInt(amount_money[0]));
				}else {
					dto.getAmountMap().put(temps[0], Integer.parseInt(amount_money[0]));
				}
				if(dto.getMoneyMap().containsKey(temps[0])){
					dto.getMoneyMap().put(temps[0], dto.getMoneyMap().get(temps[0]) + Double.parseDouble(amount_money[1]));
				}else {
					dto.getMoneyMap().put(temps[0], Double.parseDouble(amount_money[1]));
				}
			}
			dto.setTotalamount(0);
			dto.setTotalmoney(0d);
			for (String key : dto.getAmountMap().keySet()) {
				dto.setTotalamount(dto.getTotalamount() + dto.getAmountMap().get(key));
			}
			for(String key:dto.getMoneyMap().keySet()){
				dto.setTotalmoney(dto.getTotalmoney() + dto.getMoneyMap().get(key));
			}
		}
		PageData<StockReportByShopDto> pageData = new PageData<StockReportByShopDto>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public List<StockAnalysisDto> list_analysis(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		return dataDAO.list_analysis(params);
	}
	
	@Override
	public List<StockShopDto> stock_shop(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		return dataDAO.stock_shop(params);
	}
	
	@Override
	public List<Map<String, Object>> type_level_stock(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		String tp_upcode = StringUtil.trimString(params.get("tp_upcode"));
		List<T_Base_Type> childTypes = dataDAO.listTypeByUpCode(tp_upcode, companyid);
		Map<String, String> childTypeMap = new HashMap<String, String>();
		for (T_Base_Type type : childTypes) {
			childTypeMap.put(type.getTp_code(), type.getTp_name());
		}
		List<T_Base_Type> allTypes = dataDAO.listAllType(companyid);
		//根据父类编号的直接子类和所有类别，生成直接子类和其所有子类的映射关系
		Map<String, String> tpCode_RootCode = TypeVO.Convert(allTypes, Arrays.asList(childTypeMap.keySet().toArray()));
		List<Map<String, Object>> datas = dataDAO.type_level_stock(params);
		Map<String, TypeLevelDto> dtosMap = new HashMap<String, TypeLevelDto>();
		for (T_Base_Type type : childTypes) {
			TypeLevelDto dto = new TypeLevelDto();
			dto.setTp_code(type.getTp_code());
			dto.setTp_name(type.getTp_name());
			dtosMap.put(type.getTp_code(), dto);
		}
		for (Map<String, Object> item : datas) {
			String tp_code = StringUtil.trimString(item.get("tp_code"));
			String shop_code = StringUtil.trimString(item.get("dp_shop_code"));
			Integer amount = Integer.parseInt(item.get("amount").toString());
			Double money = Double.parseDouble(item.get("money").toString());
			if (!childTypeMap.containsKey(tp_code) && tpCode_RootCode.containsKey(tp_code)) {
				tp_code = tpCode_RootCode.get(tp_code);
			}
			TypeLevelDto dto = dtosMap.get(tp_code);
			if (dto == null) {
				continue;
			}
			if(dto.getAmountMap().containsKey(shop_code)){
				dto.getAmountMap().put(shop_code, dto.getAmountMap().get(shop_code)+amount);
			}else {
				dto.getAmountMap().put(shop_code, amount);
			}
			if(dto.getMoneyMap().containsKey(shop_code)){
				dto.getMoneyMap().put(shop_code, dto.getMoneyMap().get(shop_code)+money);
			}else {
				dto.getMoneyMap().put(shop_code, money);
			}
			if(!dto.getChild_type().contains(StringUtil.trimString(item.get("tp_code")))){
				dto.getChild_type().add(StringUtil.trimString(item.get("tp_code")));
			}
		}
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		Map<String, Object> item = null;
		for (T_Base_Type type : childTypes) {
			TypeLevelDto dto = dtosMap.get(type.getTp_code());
			//数量
			item = new HashMap<String, Object>();
			item.put("id", dto.getTp_code()+"_0");
			item.put("tp_code", dto.getTp_code());
			item.put("tp_code_hid", dto.getTp_code());
			item.put("tp_name", dto.getTp_name());
			item.put("project", "数量");
			item.putAll(dto.getAmountMap());
			item.put("total", dto.getTotalAmount());
			item.put("child_type", join(dto.getChild_type()));
			resultList.add(item);
			//金额
			item = new HashMap<String, Object>();
			item.put("id", dto.getTp_code()+"_1");
			item.put("tp_code", dto.getTp_code());
			item.put("tp_code_hid", dto.getTp_code());
			item.put("tp_name", dto.getTp_name());
			item.put("project", "金额");
			item.putAll(dto.getMoneyMap());
			item.put("total", dto.getTotalMoney());
			item.put("child_type", join(dto.getChild_type()));
			resultList.add(item);
		}
		return resultList;
	}
	private String join(List<String> types){
		StringBuffer result = new StringBuffer();
		for (String item : types) {
			result.append(item).append(",");
		}
		if(result.length() > 0){
			result.deleteCharAt(result.length() - 1);
		}
		return result.toString();
	}
	
	@Override
	public PageData<ProductSingleTrackDto> single_track(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID),"连接超时，请重新登录!");
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		List<String> allDepot = dataDAO.listAllDepot(params);
		params.put("allDepot", allDepot);
		
		Map<String, Object> sumMap = dataDAO.countsum_single_track(params);
		int totalCount = Integer.parseInt(sumMap.get("totalCount").toString());
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<ProductSingleTrackDto> list = dataDAO.single_track(params);
		PageData<ProductSingleTrackDto> pageData = new PageData<ProductSingleTrackDto>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		pageData.setData(sumMap);
		return pageData;
	}
	
	@Override
	public PageData<T_Stock_DataView> data_list_sale(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		List<String> allDepot = dataDAO.listAllDepot(param);
		param.put("allDepot", allDepot);
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = dataDAO.data_list_saleCount(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Stock_DataView> list = dataDAO.data_list_sale(param);
		PageData<T_Stock_DataView> pageData = new PageData<T_Stock_DataView>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}

	@Override
	public PageData<Map<String,Object>> otherList(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		String depots = (String)param.get("data");
		List<String> dp_codes = SellVO.buildDepot(depots);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		param.put("dp_codes", dp_codes);
		NumberForm form = dataDAO.otherCount(param);
		PageInfo pageInfo = new PageInfo(Integer.parseInt(form.getCode()), _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		Map<String,Object> dataMap = new HashMap<String, Object>();
		dataMap.put("sd_amount", form.getNumber());
		
		List<T_Stock_DataView> list = dataDAO.otherList(param);
		
		List<T_Stock_DataView> allList = dataDAO.allOtherList(param);
		
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		if(null != list && list.size() > 0){
			int index = 0; 
			for(T_Stock_DataView item:list){
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("sd_code", item.getSd_code());
				map.put("pd_no", item.getPd_no());
				map.put("pd_name", item.getPd_name());
				map.put("sd_cr_code", item.getSd_cr_code());
				map.put("sd_sz_code", item.getSd_sz_code());
				map.put("sd_br_code", item.getSd_br_code());
				
				map.put("sz_name", item.getSz_name());
				map.put("cr_name", item.getCr_name());
				map.put("br_name", item.getBr_name());
				map.put("sd_amount", item.getSd_amount());
				for(T_Stock_DataView all:allList){
					if(item.getSd_code().equals(all.getSd_code())){
						map.put("sd_"+all.getSd_dp_code(), all.getSd_amount());
					}
					
					if(index < allList.size()){
						String key = "sd_"+all.getSd_dp_code();
						if(dataMap.containsKey(key)){
							Integer amount = Integer.parseInt(""+dataMap.get(key))+all.getSd_amount();
							dataMap.put(key, amount);
						}else{
							dataMap.put(key, all.getSd_amount());
						}
						index ++;
					}
				}
				mapList.add(map);
			}
		}
		PageData<Map<String,Object>> pageData = new PageData<Map<String,Object>>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(mapList);
		pageData.setData(dataMap);
		return pageData;
	}

	@Override
	public List<T_Stock_Data> listAPI(Map<String, Object> paramMap) {
		if (StringUtil.isEmpty(paramMap.get(CommonUtil.COMPANYID))) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if(StringUtil.isEmpty(paramMap.get(CommonUtil.SHOP_CODE))){
			throw new IllegalArgumentException("参数shop_code不能为null");
		}
		Integer pageSize = (Integer)paramMap.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)paramMap.get(CommonUtil.PAGEINDEX);
		paramMap.put(CommonUtil.START, (pageIndex-1)*pageSize);
		paramMap.put(CommonUtil.END, pageSize);
		return dataDAO.listAPI(paramMap);
	}
	
	@Override
	public T_Stock_Data loadByBarcodeAPI(Map<String, Object> paramMap) {
		if (StringUtil.isEmpty(paramMap.get(CommonUtil.COMPANYID))) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if(StringUtil.isEmpty(paramMap.get(CommonUtil.SHOP_CODE))){
			throw new IllegalArgumentException("参数shop_code不能为null");
		}
		return dataDAO.loadByBarcodeAPI(paramMap);
	}
	
	/**
	 * 1.查询货号颜色
	 * 2.查尺码 组
	 * 3.查杯型
	 * 4.查库存
	 * */
	@Override
	public Map<String, Object> queryAPI(Map<String, Object> paramMap) {
		List<T_Base_Color> colors = colorDAO.queryByPdCode(paramMap);
		List<T_Base_Bra> bras = braDAO.queryByPdCode(paramMap);
		List<T_Base_Size> sizes = dataDAO.querySizeByPdCode(paramMap);
		List<T_Stock_DataView> data = dataDAO.queryByPdCode(paramMap);
		paramMap.clear();
		paramMap.put("color", colors);
		paramMap.put("bra", bras);
		paramMap.put("size", sizes);
		paramMap.put("stock", data);
		return paramMap;
	}

	@Override
	public List<T_Stock_DataView> otherAPI(Map<String, Object> param) {
		return dataDAO.otherAPI(param);
	}

	@Override
	public Map<String, Object> parseSavingStockExcel(Workbook soureWorkBook,
			WritableWorkbook errsheet, T_Sys_User user, String depot_code)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Integer companyid= user.getCompanyid();
			// 得到工作簿中的第一个表索引即为excel下的sheet1,sheet2,sheet3...
			Sheet sheet = soureWorkBook.getSheet(0);
			WritableSheet errorSheet = errsheet.getSheet(0);
			// 库存导入列数为5，再多的列数不允许导入
			int columns = 5;
			int rows = sheet.getRows(); // 获取导入行数
			System.out.println("库存导入数共计" + (rows - 1) + "条!");
			if(rows <= 1){
				resultMap.put("fail", 0);// 错误条数
				resultMap.put("success", 0);// 成功条数
				return resultMap;
			}
	
			//获取导入库存需要的数据
			Map<String, Object> checkImportBarcode = dataDAO.getCheckImportStock(user,depot_code);
			
			if(checkImportBarcode == null){
				resultMap.put("fail", 0);// 错误条数
				resultMap.put("success", 0);// 成功条数
				return resultMap;
			}
			
			Map<String,Map<String,Object>> pd_nos = (Map<String,Map<String,Object>>)checkImportBarcode.get("productMap");//已有商品货号
			List<T_Stock_Data> stockDatas = (List<T_Stock_Data>)checkImportBarcode.get("stockList");//库存信息
			
			List<T_Stock_Data> inserStockList = new ArrayList<T_Stock_Data>();//存放验证成功的新增库存
			List<T_Stock_Data> updateStockList = new ArrayList<T_Stock_Data>();//存放验证成功的修改库存
			T_Stock_Data t_Stock_Data = null;
			String errorCause = "";//错误原因
			int errorRow = 1;
			int successRow = 0;//导入成功行数
			// 第一行为属性，从第二行开始
			for (int i = 1; i < rows; i++) {
				if(i%100 == 0){
					Thread.sleep(1000);
				}
				t_Stock_Data = new T_Stock_Data();
				
				if (ExcelImportUtil.isBlankRow(sheet, i, columns - 1)) {//判断是否为空行
					continue;
				}
				
				boolean tag = false;
				
				Cell cell0 = sheet.getCell(0, i);// 商品货号
				String pd_no = cell0.getContents().trim().toLowerCase();
				if("".equals(pd_no)){//商品货号不能为空
					errorCause = "源文件第"+(i+1)+"行， 商品货号不能为空！";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				if(ExcelImportUtil.checkStrRegex("^[\\dA-Za-z-._]+$", pd_no)){//货号只能输入英文、数字、.、_、-
					errorCause = "源文件第"+(i+1)+"行， 商品货号只能输入英文、数字和(. - _)符号";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				if (pd_nos.get(pd_no)==null){
					errorCause = "源文件第"+(i+1)+"行， 商品货号不存在，请重新输入";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				Map<String,Object> infoMap = pd_nos.get(pd_no);//获取货号对应的尺码、颜色、杯型、code等信息
				String pd_code = (String)infoMap.get("pdCode");
				t_Stock_Data.setSd_pd_code(pd_code);
				
				Cell cell1 = sheet.getCell(1, i);//颜色
				String cr_name = cell1.getContents().trim();
				String cr_code = "";
				Map<String,String> colorMap=(Map<String,String>)infoMap.get("colorMap");//获取货号颜色
				if(!"".equals(cr_name)){
					cr_code=StringUtil.trimString(colorMap.get(cr_name));
					if (cr_code.length()==0){//颜色不存在
						errorCause = "源文件第"+(i+1)+"行，颜色不存在，请重新输入";
						ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
						errorRow++;
						continue;
					}
					t_Stock_Data.setSd_cr_code(cr_code);
				}else{
					errorCause = "源文件第"+(i+1)+"行， 请输入颜色";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				
				Cell cell2 = sheet.getCell(2, i);//尺码
				String sz_name = cell2.getContents().trim();
				String sz_code = "";
				if(!"".equals(sz_name)){
					Map<String,String> sizeMap=(Map<String,String>)infoMap.get("sizeMap");//获取货号尺码
					sz_code=StringUtil.trimString(sizeMap.get(sz_name));
					if (sz_code.length()==0){//尺码不存在
						errorCause = "源文件第"+(i+1)+"行，尺码不存在，请重新输入";
						ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
						errorRow++;
						continue;
					}
					t_Stock_Data.setSd_sz_code(sz_code);
				}else{
					errorCause = "源文件第"+(i+1)+"行， 请输入尺码";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				
				Cell cell3 = sheet.getCell(3, i);//杯型
				String br_name = cell3.getContents().trim();
				String br_code = "";
				Map<String,String> brMap=(Map<String,String>)infoMap.get("brMap");//获取货号杯型
				if(brMap.size()==0){//没有杯型
					if(br_name.length()>0){//商品中不不存在该杯型
						errorCause = "源文件第"+(i+1)+"行， 商品没有杯型，请重新输入";
						ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
						errorRow++;
						continue;
					}
				}else{//有杯型
					if(!"".equals(br_name)){
						tag = false;
						br_code=StringUtil.trimString(brMap.get(br_name));
						if (br_code.length()==0){//杯型不存在
							errorCause = "源文件第"+(i+1)+"行，杯型不存在，请重新输入";
							ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
							errorRow++;
							continue;
						}
						t_Stock_Data.setSd_br_code(br_code);
					}else{
						errorCause = "源文件第"+(i+1)+"行， 请输入杯型";
						ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
						errorRow++;
						continue;
					}
				}
				
				Cell cell4 = sheet.getCell(4, i);//数量
				String amount = cell4.getContents().trim();
				if("".equals(amount)){
					errorCause = "源文件第"+(i+1)+"行， 数量不能为空，请修改！";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				try {
					Integer.parseInt(amount);
				} catch (Exception e) {
					errorCause = "源文件第"+(i+1)+"行， 数量只允许输入数字，请修改！";
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, errorRow, columns, errorCause);
					errorRow++;
					continue;
				}
				t_Stock_Data.setSd_amount(Integer.parseInt(amount));
				String subcode = pd_code+cr_code+sz_code+br_code;
				t_Stock_Data.setSd_code(subcode);
				t_Stock_Data.setSd_dp_code(depot_code);
				t_Stock_Data.setSd_date(DateUtil.getCurrentTime());
				t_Stock_Data.setCompanyid(companyid);
				//判断库存中是否存在此条数据,如果存在则更新，否则新增
				tag = false;
				for(int j=0;j<stockDatas.size();j++){
					if(stockDatas.get(j).getSd_br_code() == null){
						stockDatas.get(j).setSd_br_code("");
					}
					if(pd_code.equals(stockDatas.get(j).getSd_pd_code()) && cr_code.equals(stockDatas.get(j).getSd_cr_code())
							&& sz_code.equals(stockDatas.get(j).getSd_sz_code()) && br_code.equals(stockDatas.get(j).getSd_br_code())){
						tag = true;
						break;
					}
				}
				
				if(tag){//库存中已存在修改
					updateStockList.add(t_Stock_Data);
				}else{//新增
					inserStockList.add(t_Stock_Data);
				}
				successRow++;
			}
			resultMap.put("updateStockList", updateStockList);//验证成功的库存（修改库存数量）
			resultMap.put("inserStockList", inserStockList);//验证成功的库存（新增）
			resultMap.put("fail", errorRow-1);// 错误条数
			resultMap.put("success", successRow);// 成功条数
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	@Override
	@Transactional
	public void save_import_stock(Map<String, Object> param) {
		List<T_Stock_Data> updateStockList = (List<T_Stock_Data>)param.get("updateStockList");//验证成功的库存（修改库存数量）
		List<T_Stock_Data> inserStockList = (List<T_Stock_Data>)param.get("inserStockList");//验证成功的库存（新增）
		T_Import_Info t_Import_Info = (T_Import_Info)param.get("t_Import_Info");
		if(updateStockList != null && updateStockList.size()>0){
			dataDAO.update_import_stock(updateStockList);
		}
		if(inserStockList != null && inserStockList.size()>0){
			dataDAO.insert_import_stock(inserStockList);
		}
		// 查询当前用户是否导入过数据
		T_Import_Info info = importInfoDAO.queryImportInfo(param);
		if(info != null){
			String temp_uploaddir = CommonUtil.CHECK_BASE + CommonUtil.EXCEL_PATH;
			String last_error_filename = temp_uploaddir + File.separator + info.getIi_error_filename();
			File last_error_file = new File(last_error_filename);
			if (last_error_file.exists()) {
				last_error_file.delete();
			}
			ExcelImportUtil.deleteFile(last_error_file);
			importInfoDAO.updateImportInfo(t_Import_Info);
		}else {
			importInfoDAO.saveImportInfo(t_Import_Info);
		}
	}
}
